<template>
  <div class="inventory-form">
    <!-- 顶部导航 -->
    <div class="header-actions">
      <router-link to="/main/xingzheng/gudingzichan" class="back-link"
        >返回</router-link
      >
    </div>
    <div style="text-align: right">
      <el-button type="primary" @click="saveData">保存</el-button>
      <el-button @click="goToList">列表</el-button>
      <!-- 新增导出 PDF 按钮 -->
      <el-button type="success" @click="exportToPDF">导出 PDF</el-button>
    </div>
    <div class="pdf">
      <h2 class="page-title">成品入库单</h2>
      <!-- 表单信息 -->
      <table class="info-table" border="1">
        <thead>
          <tr>
            <th>项目</th>
            <th>信息</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>物资：</td>
            <td><input v-model="formData.goods" :disabled="isView" /></td>
            <td rowspan="7" class="copy-info">
              <span
                >①<br />存<br />联<br />白<br />②<br />财<br />务<br />红<br />③<br />货<br />仓<br />黄<br />④<br />回<br />单</span
              >
            </td>
          </tr>
          <tr>
            <td>NO：</td>
            <td><input v-model="formData.inventoryNo" :disabled="isView" /></td>
          </tr>
          <tr>
            <td>日期：</td>
            <td>
              <el-date-picker
                v-model="formData.inventoryDate"
                type="date"
                placeholder="选择日期"
                :disabled="isView"
              ></el-date-picker>
            </td>
          </tr>
          <tr>
            <td>连续号：</td>
            <td>
              <input v-model="formData.serialNumber" :disabled="isView" />
            </td>
          </tr>
          <tr>
            <td>提货单位及部门：</td>
            <td>
              <input
                v-model="formData.pickupUnit"
                style="width: 100%"
                :disabled="isView"
              />
            </td>
          </tr>
          <tr>
            <td>发票号码或生产单号码：</td>
            <td>
              <input
                v-model="formData.invoiceProductionNumber"
                style="width: 100%"
                :disabled="isView"
              />
            </td>
          </tr>
          <tr>
            <td>备注：</td>
            <td>
              <input
                v-model="formData.remark"
                style="width: 100%"
                :disabled="isView"
              />
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 操作按钮 -->
      <div v-if="!isView" class="action-buttons">
        <button @click="addItem">新增</button>
        <button @click="deleteSelectedItems">删除选中</button>
      </div>
      <!-- 明细表格 -->
      <table class="detail-table" border="1">
        <thead>
          <tr>
            <th v-if="!isView">
              <input
                type="checkbox"
                v-model="isAllChecked"
                @change="toggleAllCheck"
              />
            </th>
            <th>编号</th>
            <th>名称及规格</th>
            <th>单位</th>
            <th>交库</th>
            <th>实收</th>
            <th>单价</th>
            <th>金额</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in formData.itemList" :key="index">
            <td v-if="!isView">
              <input
                type="checkbox"
                v-model="item.isChecked"
                @change="updateAllCheckedStatus"
              />
            </td>
            <td><input v-model="item.code" :disabled="isView" /></td>
            <td><input v-model="item.nameSpec" :disabled="isView" /></td>
            <td><input v-model="item.unit" :disabled="isView" /></td>
            <td>
              <input
                v-model="item.deliveredQuantity"
                type="number"
                :disabled="isView"
              />
            </td>
            <td>
              <input
                v-model="item.acceptedQuantity"
                type="number"
                :disabled="isView"
              />
            </td>
            <td>
              <input
                v-model="item.unitPrice"
                type="number"
                :disabled="isView"
              />
            </td>
            <td>
              <input v-model="item.amount" type="number" :disabled="isView" />
            </td>
          </tr>
        </tbody>
      </table>
      <!-- 底部信息 -->
      <div class="footer-info">
        <div>
          <label>财务部 门主管：</label><br />
          <input v-model="formData.financeSupervisor" :disabled="isView" />
        </div>
        <div>
          <label>记账</label>
        </div>
        <div>
          <label>保管部门 主 管：</label><br />
          <input v-model="formData.storageSupervisor" :disabled="isView" />
        </div>
        <div>
          <label>发货人：</label><br />
          <input v-model="formData.sender" :disabled="isView" />
        </div>
        <div>
          <label>单位部 门主管：</label><br />
          <input v-model="formData.unitSupervisor" :disabled="isView" />
        </div>
        <div>
          <label>缴库</label>
        </div>
      </div>
      <p class="save-period">保存期限：长期</p>
    </div>
  </div>
</template>

<script>
import {
  saveProductInventory,
  getProductInventoryDetail,
} from "@/api/productInventory";
import html2pdf from "html2pdf.js";

export default {
  data() {
    return {
      formData: {
        id: null,
        goods: "",
        inventoryNo: "",
        inventoryDate: "",
        serialNumber: "",
        pickupUnit: "",
        invoiceProductionNumber: "",
        remark: "",
        financeSupervisor: "",
        storageSupervisor: "",
        sender: "",
        unitSupervisor: "",
        itemList: [
          {
            isChecked: false,
            code: "",
            nameSpec: "",
            unit: "",
            deliveredQuantity: 0,
            acceptedQuantity: 0,
            unitPrice: 0,
            amount: 0,
          },
        ],
      },
      isAllChecked: false,
      isView: false,
    };
  },
  created() {
    const id = this.$route.query.id;
    const type = this.$route.query.type;
    this.isView = type === "view";
    if (id) {
      this.getDetail(id);
    }
  },
  methods: {
    async getDetail(id) {
      try {
        const response = await getProductInventoryDetail(id);
        if (response.data) {
          this.formData = {
            ...this.formData,
            ...response.data,
          };
        }
      } catch (error) {
        this.$message.error("获取详情失败");
      }
    },
    addItem() {
      this.formData.itemList.push({
        isChecked: false,
        code: "",
        nameSpec: "",
        unit: "",
        deliveredQuantity: 0,
        acceptedQuantity: 0,
        unitPrice: 0,
        amount: 0,
      });
      this.updateAllCheckedStatus();
    },
    deleteSelectedItems() {
      if (confirm("确定要删除所选行吗？")) {
        this.formData.itemList = this.formData.itemList.filter(
          (item) => !item.isChecked
        );
        this.updateAllCheckedStatus();
      }
    },
    toggleAllCheck() {
      this.formData.itemList.forEach((item) => {
        item.isChecked = this.isAllChecked;
      });
    },
    updateAllCheckedStatus() {
      this.isAllChecked = this.formData.itemList.every(
        (item) => item.isChecked
      );
    },
    async saveData() {
      try {
        const success = await saveProductInventory(this.formData);
        if (success) {
          this.$message.success(this.formData.id ? "更新成功" : "保存成功");
          this.goToList();
        } else {
          this.$message.error(this.formData.id ? "更新失败" : "保存失败");
        }
      } catch (error) {
        this.$message.error("保存失败");
        console.error("保存失败", error);
      }
    },
    goToList() {
      this.$router.push("/main/xingzheng/rukudan/rukudanList");
    },
    // 导出 PDF 方法
    exportToPDF() {
      const element = document.querySelector(".pdf");
      const opt = {
        margin: 10,
        filename: "成品入库单.pdf",
        image: { type: "jpeg", quality: 0.98 },
        html2canvas: { scale: 2 },
        jsPDF: { unit: "mm", format: "a4", orientation: "portrait" },
      };
      html2pdf().set(opt).from(element).save();
    },
  },
};
</script>

<style scoped>
/* 全局样式 */
.inventory-form {
  font-family: "宋体", sans-serif;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  /* box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); */
  width: 210mm;
  margin: 0 auto;
}

/* 顶部导航样式 */
.header-actions {
  display: flex;
}

.back-link {
  position: static;
}

/* 页面标题样式 */
.page-title {
  text-align: center;
  color: #333;
  margin-bottom: 20px;
}

/* 表单信息表格样式 */
.info-table {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 30px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}

.info-table th,
.info-table td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: center;
}

.info-table th {
  background-color: #f2f2f2;
}

.copy-info {
  text-align: center;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 10px;
}

/* 明细表格样式 */
.detail-table {
  position: relative;
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 20px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}

.detail-table th,
.detail-table td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: center;
}

.detail-table th {
  background-color: #f2f2f2;
}

/* 底部信息样式 */
.footer-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  white-space: nowrap;
}

/* 保存期限样式 */
.save-period {
  text-align: center;
  color: #666;
}

/* 输入框样式 */
input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

input[disabled] {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
  cursor: not-allowed;
}

/* 日期选择器样式 */
.el-date-picker {
  width: 100%;
}
</style>